<script setup>
import { getCurrentRouteQuery } from '@/utils/routerUtils'
import {
  addRequireApi,
  deleteTaskApi,
  findAllWorkGroupsApi,
  findProjectTaskDetailsApi,
  findRequireGroupApi,
  findTaskRequiresApi,
  findUserByNameApi,
  updateProjectTaskApi
} from '@/apis/projectManagement'
import { onMounted, ref, watch } from 'vue'
import { Link as IconLink, Plus as IconPlus } from '@element-plus/icons-vue'
import router from '@/router'
import * as echarts from 'echarts'
import { dayjs, ElMessage, ElMessageBox, genFileId } from 'element-plus'
import avatarName from '@/components/avatarName'

const filePrefix = process.env.VUE_APP_BASE_URL
const query = getCurrentRouteQuery()
const queryParams = ref({
  taskId: query.taskId,
  status: ''
})
const xx = ref(null)
const taskDetail = ref({
  project: {},
  owner: {}
})
const taskRequiresNum = ref([])
const requireList = ref([])
const addRequireRequest = ref({})
const addRequireRef = ref()
const addProjectRef = ref()
const addRequireDialogVisible = ref(false)
const addTaskDialogVisible = ref(false)
const workGroupList = ref([])
const addProjectTaskRequest = ref({
  name: null,
  projectId: null,
  owner: null,
  groupId: null,
  date: [],
  startTime: null,
  endTime: null,
  status: null,
  description: null
})

findProjectTaskDetailsApi({id: query.taskId}).then(({data}) => {
  taskDetail.value = data
  addProjectTaskRequest.value.name = data.name
  addProjectTaskRequest.value.owner = data.owner.id
  addProjectTaskRequest.value.groupId = data.workGroup.id
  addProjectTaskRequest.value.status = data.status
  addProjectTaskRequest.value.startTime = data.startTime
  addProjectTaskRequest.value.endTime = data.endTime
  addProjectTaskRequest.value.description = data.description
  addProjectTaskRequest.value.date[0] = data.startTime
  addProjectTaskRequest.value.date[1] = data.endTime
})

watch(() => addTaskDialogVisible.value, (n, o) => {
  if (o) return

  findAllWorkGroupsApi().then(({data}) => {
    workGroupList.value = data || []
  })
  findUserByNameApi('').then(({data}) => {
    ownerList.value = data || []
  })
}, {immediate: true})

function findTaskRequireslist(queryParams) {
  findTaskRequiresApi(queryParams).then(({data}) => {
    if (!data) {
      //ElMessage.error('没有找到相关数据')
      requireList.value = []
      return
    }
    requireList.value = data.dataList || []

  })
}

findTaskRequireslist(queryParams.value)

const onGoToDetails = ({row}) => {
  console.log(row)
  router.push(`/system/projectManagement/projectTask/projectRequireDetails?id=${ row.id }&projectId=${ query.projectId }&name=${ query.name }&taskId=${ query.taskId }&groupId=${ query.groupId }&requireName=${ row.name }`)
}
const ownerList = ref([])
const ownerSearchLoading = ref(true)
const onOwnerRemoteMethod = (name) => {
  ownerSearchLoading.value = true
  findUserByNameApi(name).then(({data}) => {
    ownerList.value = data || []
  }).finally(() => {
    ownerSearchLoading.value = false
  })
}

const addRequireRules = ref({
  name: [
    {
      required: true, message: '请输入项目名称', trigger: 'blur',
    }
  ],
  status: [
    {
      required: true, message: '请选择需求状态', trigger: 'blur',
    }
  ],
  owner: [
    {
      required: true, message: '请选择项目负责人', trigger: 'blur',
    }
  ],
  description: [
    {
      required: true, message: '请输入项目描述', trigger: 'blur',
    }
  ],
  date: [
    {
      required: true, message: '请选择任务时间', trigger: 'blur',
    }
  ]
})

const addProjectRules = ref({
  name: [
    {
      required: true, message: '请输入项目名称', trigger: 'blur',
    }
  ],
  owner: [
    {
      required: true, message: '请选择项目负责人', trigger: 'blur',
    }
  ],
  groupId: [
    {
      required: true, message: '请选择项目所属工作组', trigger: 'blur',
    }
  ],
  description: [
    {
      required: true, message: '请输入项目描述', trigger: 'blur',
    }
  ],
  date: [
    {
      required: true, message: '请选择任务时间', trigger: 'blur',
    }
  ]
})

const onSubmitRequire = async (formEl) => {
  console.log(addRequireRequest.value)
  if (!formEl) return
  console.log(addRequireRequest.value.date)
  await formEl.validate((valid, fields) => {
    if (valid) {
      addRequireRequest.value.startTime = dayjs(addRequireRequest.value.date[0]).format('x')
      addRequireRequest.value.endTime = dayjs(addRequireRequest.value.date[1]).format('x')
      addRequireRequest.value.taskId = query.taskId
      addRequireApi(addRequireRequest.value).then(res => {
        addRequireDialogVisible.value = false
        findTaskRequiresApi(queryParams.value).then(({data}) => {
          requireList.value = data.dataList || []
        })
      })
    }
  })
}

const onSubmitTask = async (formEl) => {
  if (!formEl) return
  console.log(addProjectTaskRequest.value.date)
  await formEl.validate((valid, fields) => {
    if (valid) {
      addProjectTaskRequest.value.startTime = dayjs(addProjectTaskRequest.value.date[0]).format('YYYY-MM-DD HH:mm:ss')
      addProjectTaskRequest.value.endTime = dayjs(addProjectTaskRequest.value.date[1]).format('YYYY-MM-DD HH:mm:ss')
      addProjectTaskRequest.value.id = query.taskId
      addProjectTaskRequest.value.projectId = query.projectId
      updateProjectTaskApi(addProjectTaskRequest.value).then(res => {
        ElMessage.success('编辑成功！')
        addTaskDialogVisible.value = false
        findProjectTaskDetailsApi({id: query.taskId}).then(({data}) => {
          taskDetail.value = data
          addProjectTaskRequest.value.name = data.name
          addProjectTaskRequest.value.owner = data.owner.id
          addProjectTaskRequest.value.groupId = data.workGroup.id
          addProjectTaskRequest.value.status = data.status
          addProjectTaskRequest.value.startTime = data.startTime
          addProjectTaskRequest.value.endTime = data.endTime
          addProjectTaskRequest.value.description = data.description
          addProjectTaskRequest.value.date[0] = data.startTime
          addProjectTaskRequest.value.date[1] = data.endTime
        })
      })
    }
  })
}

onMounted(() => {
  const myChart = echarts.init(document.getElementById('echarts-requires-group'))
  findRequireGroupApi({groupId: query.taskId}).then(({data}) => {
    console.log(data)
    taskRequiresNum.value = data || []
    myChart.setOption({
      title: {
        text: '成员需求数量统计'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        data: taskRequiresNum.value.map(k => k.name),
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        minInterval: 1
      },
      series: [
        {
          name: '数量',
          type: 'bar',
          data: taskRequiresNum.value.map(k => k.number),
          itemStyle: {
            borderRadius: [4, 4, 0, 0] //（顺时针左上，右上，右下，左下）
          }
        }
      ]
    })
  })

})

const timeFormatter = (row) => {
  if (row.createTime) {
    return dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
  }
  return null
}

const endTimeFormatter = (row) => {
  if (row.endTime) {
    return dayjs(row.endTime).format('YYYY-MM-DD HH:mm:ss')
  }
  return null
}


const requireStatusFormatter = (row) => {

  const status = row.status
  if (status === 0) {
    return '已排期'
  }
  if (status === 1) {
    return '进行中'
  }
  if (status === 2) {
    return '已完成'
  }
  if (status === 3) {
    return '已延期'
  }
}

const projectImageFileRef = ref()
const onImageFileExceed = (files) => {
  const file = files[0]
  file.uid = genFileId()
  projectImageFileRef.value.clearFiles()
  projectImageFileRef.value.handleStart(file)
}
const onChangeImageFileUpload = (uploadFile) => {
  addRequireRequest.value.documentFile = uploadFile.raw
}

const deleteTask = () => {
  ElMessageBox.confirm(
      '请确认是否删除任务',
      '删除任务',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }
  )
      .then(() => {
        deleteTaskApi({id: taskDetail.value.id}).then(res => {
          ElMessage({
            type: 'info',
            message: '删除成功',
          })
          router.back()
        })
      }).catch((action) => {
  })
}

const resetQueryParams = () => {
  queryParams.value = {
    taskId: query.taskId,
    status: ''
  }
  findTaskRequireslist(queryParams.value)
}

//选择状态选项后直接搜素

</script>

<template>
  <el-breadcrumb separator="/" style="margin-bottom: 36px;">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: `/system/projectManagement/projectTask`, query: { id: query.projectId } }">项目任务
    </el-breadcrumb-item>
    <el-breadcrumb-item>{{ query.name }}</el-breadcrumb-item>
    <!--    <el-breadcrumb-item>{{ updateProjectDetailsRequest.name }}</el-breadcrumb-item>-->
  </el-breadcrumb>
  <el-steps style="width: 100%; margin-bottom: 12px;" space="33%"
            :active="taskDetail.status === 3 ? 3 : taskDetail.status + 1" finish-status="success" align-center>
    <el-step title="未开始">
      <template #description>
        <div v-if="taskDetail.status === 0">
          最近更新时间：{{ dayjs(taskDetail.updateTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
    <el-step title="进行中">
      <template #description>
        <div v-if="taskDetail.status === 1">
          最近更新时间：{{ dayjs(taskDetail.updateTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
    <el-step title="已完成" v-if="taskDetail.status !== 3">
      <template #description>
        <div v-if="taskDetail.status === 2">
          实际完成时间：{{ dayjs(taskDetail.updateTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
    <el-step title="已逾期" v-if="taskDetail.status === 3">
      <template #description>
        <div>
          预计完成时间：{{ dayjs(taskDetail.endTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
  </el-steps>
  <div style="display: flex;">
    <div style="flex: 1; margin-right: 12px;">
      <el-card shadow="hover" body-style="display: flex; justify-content: space-between;">
        <el-form label-position="left" label-width="auto" :model="taskDetail" class="demo-form-inline">
          <el-form-item label="任务名称">
            <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
              {{ taskDetail.name }}
            </div>
          </el-form-item>
          <el-form-item label="负责人">
            <avatar-name :url="taskDetail.owner.avatar ? filePrefix + taskDetail.owner.avatar : taskDetail.owner.name"
                         :name="taskDetail.owner.name" />
          </el-form-item>
          <el-form-item label="所属项目">
            <el-button :icon="IconLink" type="primary"
                       @click="router.push(`/system/projectManagement/projectDetails?id=${taskDetail.project.id}`)"
                       style="border-radius: 5px;">
              <template #default>
                <div style="max-width: 64px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{
                    taskDetail.project.name
                  }}
                </div>
              </template>
            </el-button>
          </el-form-item>
          <el-form-item label="创建时间">
            {{ dayjs(taskDetail.createTime).format('YYYY/MM/DD HH:mm:ss') }}
          </el-form-item>
          <el-form-item label="开始时间">
            {{ taskDetail.startTime }}
          </el-form-item>
          <el-form-item label="预计结束时间">
            {{ taskDetail.endTime }}
          </el-form-item>
          <el-form-item label="任务描述">
            {{ taskDetail.description }}
          </el-form-item>
        </el-form>
        <div v-if="taskDetail.operateAuth === 1">
          <el-button @click="addTaskDialogVisible = true" size="small" type="primary">编辑</el-button>
        </div>
      </el-card>
      <el-card style="margin-top: 12px;" shadow="hover">
        <div id="echarts-requires-group" style="height: 268px;">

        </div>
      </el-card>
    </div>
    <div style="flex: 2">
      <el-card shadow="hover">
        <div style="display: flex; justify-content: space-between;">
          <h3 style="margin-left: 11px; margin-bottom: 12px;">需求目录</h3>
          <el-button @click="addRequireDialogVisible = true" type="primary"
                     size="small">添加
          </el-button>
        </div>
        <div>
          <el-form :model="queryParams" :inline="true" label-width="100px">


            <el-row>
              <el-col :span="6">
                <el-form-item label="状态:">
                  <el-select class="select-width-style" v-model="queryParams.status" placeholder="请选择" size="middle"
                             @change="findTaskRequireslist(queryParams)"
                  >
                    <el-option v-for="item in [
                  { value: ' ', name: '全部' },
                    { value: 1, name: '进行中' },
                    { value: 2, name: '已完成' },
                    { value: 3, name: '已延期' }
                  ]" :key="item.value" :label="item.name" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="需求单号:">
                  <el-input v-model="queryParams.id" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="6">

                <el-form-item label="需求名:">
                  <el-input v-model="queryParams.name" placeholder="请输入" />
                </el-form-item>
              </el-col>
              <el-col :span="4">

                <el-form-item class="form-btn-right">
                  <el-button type="success" @click="findTaskRequireslist(queryParams)">搜索</el-button>
                  <el-button type="primary" @click="resetQueryParams">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>


            <!-- <el-col :span="2">
            </el-col>
            <el-col :span="11">
              <el-date-picker style="width: 515px;" v-model="queryParams.date" type="datetimerange"
                range-separator="-" start-placeholder="需求开始时间" end-placeholder="需求预计结束时间" />
            </el-col> -->


          </el-form>

        </div>
        <div style="width: 900px;">
          <el-table :data="requireList" stripe style="width: 100%; overflow-x: scroll;" max-height="533">
            <el-table-column prop="id" label="需求单号" fixed align="center" />
            <el-table-column prop="name" label="名称" width="120" />
            <el-table-column prop="description" label="描述" width="300" />

            <el-table-column prop="startTime" label="创建时间" width="180" :formatter="timeFormatter" />
            <el-table-column prop="endTime" label="预计结束时间" width="180" :formatter="endTimeFormatter" />
            <el-table-column prop="status" label="状态" width="100" :formatter="requireStatusFormatter" />
            <el-table-column prop="owner.name" width="100" label="负责人">
              <template #default="scope">
                <avatar-name :url="scope.row.owner.avatar ? filePrefix + scope.row.owner.avatar : scope.row.owner.name"
                             :name="scope.row.owner.name" />
              </template>
            </el-table-column>

            <el-table-column width="100" label="操作">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="onGoToDetails(scope)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
  <div style="display: flex; justify-content: center;">
    <el-button v-if="taskDetail.operateAuth === 1" @click="deleteTask" type="danger" style="width: 200px;">删除任务
    </el-button>
  </div>
  <el-dialog v-model="addRequireDialogVisible" title="添加需求" draggable overflow width="700px">
    <el-form ref="addRequireRef" inline :rules="addRequireRules" :model="addRequireRequest" label-position="top"
             label-width="auto">
      <el-form-item label="需求名称" prop="name">
        <el-input style="width: 660px;" v-model="addRequireRequest.name" placeholder="输入需求名称"></el-input>
      </el-form-item>

      <el-form-item label="需求负责人" prop="owner">
        <el-select v-model="addRequireRequest.owner" :remote-method="onOwnerRemoteMethod" placeholder="搜索负责人"
                   :loading="ownerSearchLoading" style="width: 194px" clearable filterable remote>
          <el-option v-for="owner in ownerList" :key="owner.id" :label="owner.name" :value="owner.id">
            <span style="float: left">{{ owner.name }}</span>
            <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
              {{ owner.username }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="需求状态" prop="status">
        <el-select v-model="addRequireRequest.status" style="width: 200px">
          <el-option label="已排期" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="已延期" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="需求优先级" prop="priority" style="margin-right: 0">
        <el-select v-model="addRequireRequest.priority" style="width: 200px">
          <el-option label="低" :value="0" />
          <el-option label="中" :value="1" />
          <el-option label="高" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="需求时间" prop="date">
        <el-date-picker style="width: 638px;" v-model="addRequireRequest.date" type="datetimerange" range-separator="-"
                        start-placeholder="需求开始时间" end-placeholder="需求预计结束时间" />
      </el-form-item>

      <el-form-item label="需求描述" prop="description">
        <el-input style="width: 660px;" v-model="addRequireRequest.description" type="textarea" :rows="4"
                  placeholder="描述下需求吧"></el-input>
        <!--        <el-input v-model="form.name" autocomplete="off"/>-->
      </el-form-item>


      <el-form-item label="需求文档" prop="documentFile">
        <el-upload action="#" :limit="1" :on-exceed="onImageFileExceed" :on-change="onChangeImageFileUpload"
                   ref="projectImageFileRef" accept=".doc,.docx,.pdf,.txt" :auto-upload="false">
          <el-button style="width: 660px" :icon="IconPlus">上传</el-button>


        </el-upload>
      </el-form-item>
      <!--      <el-form-item label="需求设计方案" prop="scheme">-->
      <!--        <el-input style="width: 660px;" v-model="addRequireRequest.scheme" type="textarea" :rows="4"-->
      <!--                  placeholder="描述下需求方案吧"></el-input>-->
      <!--        &lt;!&ndash;        <el-input v-model="form.name" autocomplete="off"/>&ndash;&gt;-->
      <!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" size="small" @click="addRequireDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="onSubmitRequire(addRequireRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="addTaskDialogVisible" title="添加任务" draggable overflow width="700px">
    <el-form ref="addProjectRef" inline :rules="addProjectRules" :model="addProjectTaskRequest" label-position="top">
      <el-form-item label="任务名称" prop="name">
        <el-input style="width: 660px;" v-model="addProjectTaskRequest.name" placeholder="输入任务名称"></el-input>
      </el-form-item>

      <el-form-item label="任务负责人" prop="owner">
        <el-select v-model="addProjectTaskRequest.owner" :remote-method="onOwnerRemoteMethod" placeholder="搜索负责人"
                   :loading="ownerSearchLoading" style="width: 200px" clearable filterable remote>
          <el-option v-for="owner in ownerList" :key="owner.id" :label="owner.name" :value="owner.id">
            <span style="float: left">{{ owner.name }}</span>
            <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
              {{ owner.username }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务所属工作组" prop="groupId">
        <el-select v-model="addProjectTaskRequest.groupId" placeholder="选择项目所属工作组" style="width: 200px"
                   clearable>
          <el-option v-for="group in workGroupList" :key="group.id" :label="group.gName" :value="group.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status" style="margin-right: 0">
        <el-select v-model="addProjectTaskRequest.status" style="width: 194px">
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="已逾期" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务时间" prop="date">
        <el-date-picker style="width: 638px;" v-model="addProjectTaskRequest.date" type="datetimerange"
                        range-separator="-" start-placeholder="任务开始时间" end-placeholder="任务预计结束时间" />
      </el-form-item>

      <el-form-item label="任务描述" prop="description">
        <el-input style="width: 660px;" v-model="addProjectTaskRequest.description" type="textarea" :rows="4"
                  placeholder="描述下任务吧"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" size="small" @click="addTaskDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="onSubmitTask(addProjectRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
:deep(.el-textarea__inner) {
  resize: none;
}

.el-form-item {
  margin-bottom: 8px;
}

.form-btn-right {
  float: right;
}

/* 自定义样式类 */
.select-width-style {
  width: 150px;
  /* 或者你想要的具体宽度，如 200px */
}
</style>